package com.beiji.usercentert.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beiji.usercentert.commoon.BaseResponse;
import com.beiji.usercentert.commoon.ErrorCode;
import com.beiji.usercentert.exception.BusinessException;
import com.beiji.usercentert.model.domain.Team;
import com.beiji.usercentert.model.domain.User;
import com.beiji.usercentert.model.domain.UserTeam;
import com.beiji.usercentert.model.request.TeamAddRequest;
import com.beiji.usercentert.model.dto.TeamQuery;
import com.beiji.usercentert.model.request.TeamJoinRequest;
import com.beiji.usercentert.model.request.TeamQuitRequest;
import com.beiji.usercentert.model.request.TeamUpdateRequest;
import com.beiji.usercentert.model.vo.TeamUserVO;
import com.beiji.usercentert.service.TeamService;
import com.beiji.usercentert.service.UserService;
import com.beiji.usercentert.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/team")
@Slf4j
public class TeamController {

    @Resource
    private TeamService teamService;
    @Resource
    private UserService userService;
    @Resource
    private UserTeamService userTeamService;

    /**
     * 新增队伍
     *
     * @param teamAddRequest
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        if (teamAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //获得当前登录用户
        User loginUser = userService.getLoginUser(request);
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        Long teamId = teamService.addTeam(team, loginUser);

        return BaseResponse.success(teamId);
    }

    /**
     * 更新队伍信息
     *
     * @param teamUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        if (teamUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.updateTeam(teamUpdateRequest, loginUser);

        if (!result) {
            throw new BusinessException(ErrorCode.NULL_DATA, "修改失败");
        }

        return BaseResponse.success(true);
    }


    @GetMapping("/get")
    public BaseResponse<Team> getTeamById(Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Team team = teamService.getById(id);

        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_DATA, "查询失败");
        }

        return BaseResponse.success(team);
    }

    /**
     * 查询队伍
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> listTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //获得当前用户，并判断当前用户是否为管理
        boolean isAdmin = userService.isAdmin(userService.getLoginUser(request));

        List<TeamUserVO> teamUserVOList = teamService.listTeams(teamQuery, isAdmin);

        return BaseResponse.success(teamUserVOList);
    }

    /**
     * 分页查询队伍
     * @param teamQuery
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<Team>> listTeamsPage(TeamQuery teamQuery) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamQuery, team);
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> teamPage = teamService.page(new Page<>(teamQuery.getPageNum(), teamQuery.getPageSize()), queryWrapper);

        if (teamPage == null) {
            throw new BusinessException(ErrorCode.NULL_DATA);
        }

        return BaseResponse.success(teamPage);
    }


    /**
     * 加入队伍
     *
     * @param teamJoinRequest
     * @param request
     * @return
     */
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //获得当前用户
        User loginUser = userService.getLoginUser(request);

        boolean result = teamService.joinTeam(teamJoinRequest, loginUser);

        return BaseResponse.success(result);
    }


    /**
     * 退出队伍
     * @param teamQuitRequest
     * @param request
     * @return
     */
    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        //非空判断
        if (teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //获得当前登录用户
        User loginUser = userService.getLoginUser(request);
        boolean result = teamService.quitTeam(teamQuitRequest, loginUser);

        return BaseResponse.success(result);
    }

    /**
     * 注销队伍
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody Long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //获得当前登录用户
        User loginUser = userService.getLoginUser(request);

        boolean result = teamService.deleteTeam(id, loginUser);

        if (!result) {
            throw new BusinessException(ErrorCode.NULL_DATA, "删除失败");
        }

        return BaseResponse.success(true);
    }

    /**
     * 查询创建的队伍
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list/my/create")
    public BaseResponse<List<TeamUserVO>> listCreateTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //获得当前用户
        User loginUser = userService.getLoginUser(request);
        teamQuery.setUserId(loginUser.getId());

        List<TeamUserVO> teamUserVOList = teamService.listCreateOrJoinTeam(teamQuery);

        return BaseResponse.success(teamUserVOList);
    }

    /**
     * 查询加入的队伍
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVO>> listJoinTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //获得当前用户
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();

        //根据队伍和用户的关系查询加入的队伍的id
        List<UserTeam> userTeamList = userTeamService.lambdaQuery().eq(UserTeam::getUserId, userId).list();

        //获得队伍id
        Set<Long> setId = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());
        teamQuery.setIdList(setId);

        List<TeamUserVO> teamUserVOList = teamService.listCreateOrJoinTeam(teamQuery);;

        return BaseResponse.success(teamUserVOList);
    }
}
